<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler {
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        BusinessException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register() {
        $this->reportable(function (Throwable $e) {
            //
        });
    }


    public function render($request, Throwable $e) {
//        (new ValidationException())->validator->errors()->
        if ($e instanceof ValidationException) {
            return response()->json([
                'code' => $e->getCode(),
                'msg' => '参数验证失败',
                'errors' => $e->validator->errors(),
            ],
                422);
        }
        if ($e instanceof ConfigException) {
            // dd($e->getTrace());
            return response()->json([
                'code' => -1,
                'msg' => $e->getMessage(),
            ],
            );
        }
        if ($e instanceof BusinessException) {
            // dd($e->getTrace());
            return response()->json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
            ]);
        }
        if ($e instanceof NotFoundHttpException && config('app.env') == 'production') {
            return response()->json([
                'code' => $e->getCode(),
                'msg' => '请求 url 不存在',
            ],
                404);

        }

        if ($e instanceof ModelNotFoundException && config('app.env') == 'production') {
            return response()->json([
                'code' => $e->getCode(),
                'msg' => 'Entry for ' . $e->getModel() . ' not found',
            ],
                404);
        }
        if ($e instanceof \Error && config('app.env') == 'production') {
            return response()->json([
                'code' => -1,
                'msg' => 'server error',
            ]);
        }
//        AuthenticationException
//        if ($e instanceof BindingResolutionException) {
//            return response()->json([
//                                        'error' => 'Entry for '.str_replace('App\\', '', $exception->getModel()).' not found'], 404);
//        }
////        return response()->json(['code'=>11]);
//        dd($e);
        return parent::render($request, $e); // TODO: Change the autogenerated stub
    }
}
